import { config } from 'process';
import { Controller, Get, Res, Req } from '@nestjs/common';
import { NotAuthorized } from 'src/decorator/roles.decorator';
import { ApiConfigKit, WeChat } from 'tnwx';
import jsSHA from "jssha";
import { v1 as uuidv1 } from 'uuid';

@NotAuthorized()
@Controller('wx')
export class WxController {

    /**
     *  微信公众号服务器验证回调
     */
    @Get('cb')
    callback(@Req() req) {
        console.log('req', req.query);
        const token = 'tubangyangche';
        const { signature, timestamp, nonce, echostr } = req.query;
        //2.将token、timestamp、nonce三个参数进行字典序排序
        let array = [token, timestamp, nonce];
        array.sort();
        //3.将三个参数字符串拼接成一个字符串进行sha1加密
        let tempStr = array.join('');
        let shaObj = new jsSHA('SHA-1', 'TEXT');
        shaObj.update(tempStr);
        const scyptoString = shaObj.getHash('HEX');

        if (signature === scyptoString) {
            return echostr;
        } else {
            return false;
        } 
    }

    @Get('jssdk')
    async config(@Req() req) {
        console.log(req.query)
        const url = req.query.url;
        const appId = 'wx8bc01fecc1080870';
        const timestamp = String(parseInt(String(Date.now()/1000)));
        const nonceStr = uuidv1();
        const signature =  await WeChat.jssdkSignature(nonceStr,timestamp,url);
        return  {
            appId,
            timestamp, 
            nonceStr,
            signature,
        }
    }
}
